package com.iplant.base.utils.general;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iplant.base.utils.BaseConfigConstans;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtil {

	private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

	// 是否启用远程ftp上传
	public static int UseFTP = 0;

	static {

		UseFTP = BaseConfigConstans.FTPUploadEnable;
	}

	// 服务器ip地址
	private String url = "";

	// "192.168.189.111";
	// FTP端口，默认是21（注意：SSH默认22） port = 21;
	private int port = 0;

	// 登录用户名
	private String username = "";
	// 登录密码
	private String password = "";

	private String dir = "";

	private FTPClient ftpClient = null;

	private FtpUtil(String url, int port, String username, String password, String wDIC) {
		if (StringUtils.isEmpty(url))
			this.url = url;
		if (port >= 0)
			this.port = port;
		if (StringUtils.isEmpty(username))
			this.username = username;
		if (StringUtils.isEmpty(password))
			this.password = password;
		if (StringUtils.isEmpty(wDIC))
			this.dir = wDIC;
		ftpClient = new FTPClient();
	}

	public static FtpUtil getInstance(String url, int port, String username, String password, String wDIC) {
		return new FtpUtil(url, port, username, password, wDIC);
	}

	// 将字符串写入文件上传至服务器
	/**
	 * 
	 * @param wFile
	 * @param wDIC      无/前缀有/后缀
	 * @param wFileName 无/前缀
	 * @return
	 */
	public boolean upload(File wFile, String wDIC, String wFileName) {

		boolean success = false;
		try {

			if (UseFTP != 1)
				return success;

			int reply;

			ftpClient.setControlEncoding("UTF-8");
			// 连接FTP服务器
			ftpClient.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftpClient.login(username, password);
			// 如果reply的值是230,表示连接成功，530可能是用户名或者密码错误
			// 500可能是/home/test目录不存在
			reply = ftpClient.getReplyCode();
			System.out.println(reply);

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return success;
			}

			InputStream input = new FileInputStream(wFile);

			ftpClient.enterLocalPassiveMode();
			// 需要添加这行代码，不然上传的文件为空
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

			if (!dir.endsWith("/"))
				dir = dir + "/";

			this.CreateDirecroty(dir + wDIC);

			boolean g = ftpClient.storeFile(dir + wDIC + wFileName, input);

			logger.debug("上传服务器：" + g);
			input.close();
			ftpClient.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}

	private boolean changeWorkingDirectory(String directory) {
		boolean flag = true;
		try {
			flag = ftpClient.changeWorkingDirectory(directory);
			if (flag) {
				logger.debug("进入文件夹" + directory + " 成功！");

			} else {
				logger.debug("进入文件夹" + directory + " 失败！");
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return flag;
	}

	// 创建目录
	private boolean makeDirectory(String dir) {
		boolean flag = true;
		try {
			flag = ftpClient.makeDirectory(dir);
			if (flag) {
				logger.debug("创建文件夹" + dir + " 成功！");

			} else {
				logger.debug("创建文件夹" + dir + " 失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	// 创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
	private boolean CreateDirecroty(String remote) throws IOException {
		boolean success = true;
		String directory = remote + "/";
//	        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
		// 如果远程目录不存在，则递归创建远程服务器目录
		if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
			} else {
				start = 0;
			}
			end = directory.indexOf("/", start);
			String path = "";
			String paths = "";
			while (true) {

				String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
				path = path + "/" + subDirectory;
				if (!existFile(path)) {
					if (makeDirectory(subDirectory)) {
						changeWorkingDirectory(subDirectory);
					} else {
						logger.debug("创建目录[" + subDirectory + "]失败");
						changeWorkingDirectory(subDirectory);
					}
				} else {
					changeWorkingDirectory(subDirectory);
				}

				paths = paths + "/" + subDirectory;
				start = end + 1;
				end = directory.indexOf("/", start);
				// 检查所有目录是否创建完毕
				if (end <= start) {
					break;
				}
			}
		}
		return success;
	}

	// 判断ftp服务器文件是否存在
	public boolean existFile(String path) throws IOException {
		boolean flag = false;
		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		if (ftpFileArr.length > 0) {
			flag = true;
		}
		return flag;
	}

}
